<script lang="ts" setup>
import { ref, nextTick, computed } from 'vue'
import { ElTreeV2 } from 'element-plus'
import { ElMessage } from 'element-plus'
import { JnmlQueryResult, WsgjmlQueryParam, WsgjmlQueryResult } from '@/api/xtpz-dto'
import xtpzService from '@/api/xtpz'
import TreeUtil from '@/utils/tree'
import type { TreeNodeData } from 'element-plus/es/components/tree-v2/src/types'
import { cloneDeep } from 'lodash'
// 入参
interface Prop {
  currrentMbpz: any
  isShowFooter: boolean
}
// 入参
const props = defineProps<Prop>()
const emit = defineEmits(['refresh'])
// 生命周期
/*
 * 打开弹框
 */
const loading = ref<boolean>(false)
const isLoadShow = ref<boolean>(false)
const dialogVisible = ref<boolean>(false)
// 弹框名称
// 弹框类型
const currentRow = ref<JnmlQueryResult>()
const openDialog = (row: JnmlQueryResult) => {
  currentRow.value = row
  filterTree()
  queryWsgjml()
  // queryWsgjmx(row)
  dialogVisible.value = true
}
/**
 * 表单
 */
const form = ref<WsgjmlQueryParam>({
  gjz: '',
  ajlbbm: '',
  checkbox: false,
})
/**
 * 查询文书挂接目录
 */
const treeData = ref<WsgjmlQueryResult[]>([])
const treeRightData = ref<WsgjmlQueryResult[]>([])
const queryWsgjml = () => {
  const params = {
    gjz: form.value.gjz,
    ajlbbm: props.currrentMbpz.ajlbbm || '',
    // ajlbbm: '2001',
  }
  isLoadShow.value = true
  xtpzService
    .queryWsgjml(params)
    .then((res) => {
      if (res) {
        if (props.isShowFooter) {
          res.data = res.data.map((item) => {
            return {
              ...item,
              disabled: false,
            }
          })
        } else {
          res.data = res.data.map((item) => {
            return {
              ...item,
              disabled: true,
            }
          })
        }
        treeRightData.value = res.data
        treeData.value = TreeUtil.getTreeData(res.data, 'mlbh', 'fmlbh')
        defaultExpandedKeys.value = res.data.map((el: any) => el.mlbh)
        queryWsgjmx(currentRow.value as JnmlQueryResult)
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      isLoadShow.value = false
    })
}
/**
 * 获取详情
 */
const fjList = ref<any[]>([])
const queryWsgjmx = (row: JnmlQueryResult) => {
  const params = {
    jnmlbm: row.jnmlbm,
  }
  xtpzService
    .queryWsgjmx(params)
    .then((res: any) => {
      // 默认绑定
      if (res.data && res.data.length > 0) {
        nextTick(() => {
          checkNodes.value = res.data.filter(
            (el: any) => el.gjlx.trim() === '1' || el.gjlx.trim() === '2' || el.gjlx.trim() === '3',
          )
          checkFjNodes.value = res.data.filter((el: any) => el.gjlx.trim() === '3')
          const value = checkNodes.value?.map((el: any) => el.mlbh)
          treeRef.value?.setCheckedKeys(value)
          const checkZjData = {
            checkedKeys: value,
            halfCheckedKeys: [],
          }
          checkChange(null, checkZjData)
        })
        // const flatArr = TreeUtil.flatten(treeData.value).map((el) => {
        //   return {
        //     ...el,
        //     children: [],
        //   }
        // })
        // const findCommonList = findCommonData(flatArr, res.data)
        // checkNodes1.value = TreeUtil.getTreeData(findCommonList, 'mlbh', 'fmlbh')
      } else {
        checkNodes.value = []
        checkFjNodes.value = []
        nextTick(() => {
          treeRef.value?.setCheckedKeys([])
        })
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

/*
 * 验证表单
 */
const validateForm = () => {
  batchAddWsgj()
}
const defaultProps = {
  children: 'children',
  label: 'mlmc',
  value: 'mlbh',
  disabled: 'disabled',
}
/**
 * 正卷树选中
 */
const checkNodes = ref<any[]>([])
const checkNodes1 = ref<any[]>([])
const treeRef = ref()
const stemp = ref<number>(1)
const isShowCheck = ref<boolean>(false)
const qxtbShowCheck = ref<boolean>(false)
const leftCheck = ref<string[]>([])
const checkChange = (_: any, checks: any) => {
  if (checks) leftCheck.value = [...checks.checkedKeys, ...checks.halfCheckedKeys]
  nextTick(() => {
    const nodes = treeRef.value?.getCheckedNodes() as any
    const fnodes = treeRef.value?.getHalfCheckedNodes() as any
    checkNodes.value = nodes || []
    checkNodes1.value = treeRightData.value.filter((item) =>
      [...fnodes, ...nodes].find((el) => el.mlbh === item.mlbh),
    )
    if (stemp.value === 1) {
      fjList.value = TreeUtil.getTreeData(
        checkNodes1.value?.map((item) => {
          return { ...item, children: [] }
        }),
        'mlbh',
        'fmlbh',
      )
    }
    nextTick(() => {
      if (stemp.value === 1) {
        treeRightRef.value?.setCheckedKeys(checkFjNodes.value?.map((el) => el.mlbh))
        const checkFjData = {
          checkedKeys: checkFjNodes.value?.map((el: any) => el.mlbh),
          halfCheckedKeys: [],
        }
        fjCheckChange(null, checkFjData)
        stemp.value++
      } else {
        if (isShowCheck.value) {
          // qxqxShowCheck.value = false
          // if (!checkNodes.value.length) {
          //   qxtbShowCheck.value = true
          // }
          console.log(qxtbShowCheck.value, 'qxtbShowCheck')
          if (qxtbShowCheck.value) {
            treeRightRef.value?.setCheckedKeys([])
          } else {
            // treeRightRef.value?.setCheckedKeys(checkNodes.value?.map((el) => el.mlbh))
          }
        } else {
          // if (!checkNodes.value.length) {
          //   qxtbShowCheck.value = true
          // }

          console.log(111)

          if (qxtbShowCheck.value) {
            treeRightRef.value?.setCheckedKeys([])
          } else {
            console.log(checkFjNodes.value, 'checkFjNodes.value')

            const newArr = checkFjNodes.value
            treeRightRef.value?.setCheckedKeys(newArr)
          }
        }
      }
    })
  })
}
/**
 * 副卷树选中
 */
const checkFjNodes = ref<any[]>([])
const treeRightRef = ref()
const rightCheck = ref<string[]>([])
const fjCheckChange = (data: any, checks: any) => {
  rightCheck.value = [...checks.checkedKeys, ...checks.halfCheckedKeys]
  // checkFjNodes.value = [
  //   ...nonde.checkedNodes.map((item: any) => {
  //     return { ...item, children: [] }
  //   }),
  //   ...nonde.halfCheckedNodes.map((item: any) => {
  //     return { ...item, children: [] }
  //   }),
  // ]
  // console.log(treeRightRef.value?.getCheckedNodes(), 'treeRightRef.value?.getCheckedNodes()')
  // const nodes = treeRightRef.value?.getCheckedNodes() as any
  const nodes = [...checks.checkedKeys, ...checks.halfCheckedKeys]
  checkFjNodes.value = nodes
}
/**
 * 批量保存文书挂接
 */
const batchAddWsgj = () => {
  if (!checkNodes.value || checkNodes.value?.length === 0) {
    ElMessage({ type: 'warning', message: '请选择文书挂接目录' })
    return
  }
  if (!checkNodes.value[0]?.ajlbbm) {
    ElMessage({ type: 'success', message: '保存成功' })
    emit('refresh')
    handleClose()
    return
  }
  const checkZjClone = checkNodes.value?.map((el) => {
    return {
      ajlbbm: el.ajlbbm,
      jnmlbm: currentRow.value?.jnmlbm || '',
      mbpzbm: currentRow.value?.mbpzbm || '',
      mlbh: el.mlbh,
      mllx: el.mllx,
      wsmbbh: el.wsmbbh,
      gjlx: props.currrentMbpz.mblxdm === 'gd0220001' ? '1' : '2',
    }
  })
  const checkFjClone = cloneDeep(treeRightRef.value?.getCheckedNodes())?.map((el: any) => {
    return {
      ajlbbm: el.ajlbbm,
      jnmlbm: currentRow.value?.jnmlbm || '',
      mbpzbm: currentRow.value?.mbpzbm || '',
      mlbh: el.mlbh,
      mllx: el.mllx,
      wsmbbh: el.wsmbbh,
    }
  })
  // const newArr = [...checkZjClone, ...checkFjClone]
  if (checkFjClone && checkFjClone.length) {
    checkZjClone.forEach((el) => {
      checkFjClone.forEach((item: any) => {
        if (el.mlbh === item.mlbh) {
          el['gjlx'] = '3'
        }
      })
    })
  }
  const params = checkZjClone
  loading.value = true
  xtpzService
    .batchAddWsgj(params)
    .then(() => {
      ElMessage.success('保存成功')
      emit('refresh')
      handleClose()
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}
/**
 * 是否查看选中文书
 */
const switchChange = (val: boolean) => {
  treeRef.value?.filter(val)
  treeRightRef.value?.filter(val)
}
// 文字过滤
const filterTree = () => {
  treeRef.value?.filter(form.value.gjz)
  treeRightRef.value?.filter(form.value.gjz)
}
/**
 * 树节点过滤
 */
const filterNode = (value: any, data: any) => {
  let flag: any = true
  if (value) {
    if (typeof value === 'string') {
      // 文字过滤
      // let parentNode = node.parent
      // let labels = [node.label]
      // let level = 1 // 层级
      // while (level < node.level) {
      //   labels = [...labels, parentNode.label] // 当前node名字，父级node的名字
      //   parentNode = parentNode.parent
      //   level++
      // }
      // flag = labels.some((d) => d.indexOf(value) !== -1)
      flag = data[defaultProps.label].indexOf(value) !== -1
    } else if (typeof value === 'boolean') {
      // const checkArr = treeRef.value?.getCheckedNodes().map((el: any) => el.mlbh)
      flag = leftCheck.value.includes(data.mlbh)
    }
  }
  return flag
}
// 树节点过滤
const filterFNode = (value: string, data: TreeNodeData) => {
  let flag: any = true
  if (value) {
    if (typeof value === 'string') {
      // 文字过滤
      // let parentNode = node.parent
      // let labels = [node.label]
      // let level = 1 // 层级
      // while (level < node.level) {
      //   labels = [...labels, parentNode.label] // 当前node名字，父级node的名字
      //   parentNode = parentNode.parent
      //   level++
      // }
      flag = data[defaultProps.label].indexOf(value) !== -1
    } else if (typeof value === 'boolean') {
      // const checkArr = checkFjNodes.value?.map((el) => el.mlbh)
      // const checkArr = treeRightRef.value.getCheckedNodes().map((el: any) => el.mlbh)
      flag = rightCheck.value.includes(data.mlbh)
    }
  }
  return flag
}
const defaultExpandedKeys = ref<string[]>([])
// 同步采集到副卷 -》 取消同步
const updateGjlx = (val: any) => {
  nextTick(() => {
    if (val) {
      const nodes = treeRef.value?.getCheckedNodes() as any
      const fnodes = treeRef.value?.getHalfCheckedNodes() as any
      checkNodes1.value = treeRightData.value.filter((item) =>
        [...fnodes, ...nodes].find((el) => el.mlbh === item.mlbh),
      )
      const flattenList = cloneDeep(checkNodes1.value)?.map((el) => {
        return { ...el, children: [] }
      })
      fjList.value = TreeUtil.getTreeData(flattenList, 'mlbh', 'fmlbh')
      isShowCheck.value = true
      qxtbShowCheck.value = false
      // nextTick(() => {
      //   treeRightRef.value?.setCheckedKeys(flattenList?.map((el) => el.mlbh))
      //   rightCheck.value = flattenList?.map((el) => el.mlbh)
      //   filterTree()
      // })
    } else {
      isShowCheck.value = false
      qxtbShowCheck.value = true
      // checkFjNodes.value = treeRightRef.value.getCheckedNodes()
      // const shaixuanList = checkFjNodes.value.filter(
      //   (item) => !checkFjNodes.value.find((el) => el.mlbh === item.mlbh),
      // )
      // fjList.value = []
      nextTick(() => {
        fjList.value = []
        treeRightRef.value?.setCheckedKeys([])
        rightCheck.value = []
        filterTree()
      })
    }
  })
}
// 关闭弹窗
const handleClose = () => {
  form.value = {
    gjz: '',
    ajlbbm: '',
    checkbox: false,
  }
  checkNodes.value = []
  checkNodes1.value = []
  fjList.value = []
  stemp.value = 1
  isShowCheck.value = false
  qxtbShowCheck.value = false
  leftCheck.value = []
  rightCheck.value = []
  dialogVisible.value = false
}
const countWidth = computed(() => {
  if (props.currrentMbpz.mblxdm === 'gd0220001') {
    return '1200px'
  }
  return '800px'
})

const isShowFj = computed(() => {
  if (props.currrentMbpz.mblxdm === 'gd0220001') {
    return true
  }
  return false
})

const countContentLeft = computed(() => {
  if (props.currrentMbpz.mblxdm === 'gd0220001') {
    return '50%'
  }
  return '100%'
})

defineExpose({ openDialog })
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    title="文书挂接"
    :width="countWidth"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <div class="dialog-box">
      <div class="dialog-switch">
        <div class="dialog-header">
          <el-input
            class="small-input"
            v-model="form.gjz"
            maxlength="100"
            clearable
            placeholder="关键字查询"
            @change="filterTree"
          >
            <template #append>
              <el-button @click="filterTree" type="primary">查询</el-button>
            </template>
          </el-input>
        </div>
        <el-switch
          v-model="form.checkbox"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-text="仅显示选中文书"
          @change="switchChange"
        />
      </div>
      <div class="dialog-content">
        <div class="left" :style="{ width: countContentLeft }">
          <div class="content-juan">{{ isShowFj ? '正卷:' : '副卷:' }}</div>
          <div class="tree-box" v-loading="isLoadShow">
            <!-- default-expand-all -->
            <!--  :default-expanded-keys="defaultExpandedKeys" -->
            <el-tree-v2
              ref="treeRef"
              node-key="mlbh"
              :height="400"
              v-if="treeData.length"
              :data="treeData"
              :props="defaultProps"
              :item-size="32"
              show-checkbox
              highlight-current
              :default-expanded-keys="defaultExpandedKeys"
              :filter-method="filterNode"
              @check="checkChange"
            />
          </div>
        </div>
        <div class="center" v-if="isShowFj">
          <el-button type="primary" @click="updateGjlx(true)" v-if="isShowFooter"
            >同步采集到副卷</el-button
          >
          <el-button type="primary" @click="updateGjlx(false)" v-if="isShowFooter"
            >取消同步
          </el-button>
        </div>
        <div class="right" v-if="isShowFj">
          <div class="content-juan">副卷:</div>
          <div class="tree-box" v-loading="isLoadShow">
            <!-- default-expand-all -->
            <!-- :filter-node-method="filterNode"
              :default-expanded-keys="defaultExpandedKeys"
              @check-change="checkChange"  -->
            <el-tree-v2
              ref="treeRightRef"
              node-key="mlbh"
              v-if="fjList.length"
              :height="400"
              :data="fjList"
              :props="defaultProps"
              :item-size="32"
              show-checkbox
              highlight-current
              :filter-method="filterFNode"
              :default-expanded-keys="defaultExpandedKeys"
              @check="fjCheckChange"
            />
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button v-if="isShowFooter" type="primary" @click="validateForm" :loading="loading"
          >确定</el-button
        >
        <el-button @click="handleClose">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.dialog-box {
  width: 100%;
  height: 500px;
  display: flex;
  flex-direction: column;
  .dialog-switch {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 5px 0;
    .dialog-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .small-input {
        width: 300px;
      }
      :deep(.el-input-group__append) {
        button {
          background: #409eff;
          color: #fff;
          border-bottom-left-radius: 0;
          border-top-left-radius: 0;
          &:hover {
            background: #79bbff !important;
            color: #fff;
          }
        }
      }
    }
  }
  .dialog-content {
    width: 100%;
    height: 470px;
    display: flex;
  }
  .left {
    min-width: 430px;
    height: 100%;
    display: flex;
    flex-direction: column;
    border: 1px solid #dcdfe6;
    padding-left: 10px;
    .tree-box {
      // flex: 1;
      // flex-shrink: 0;
      height: calc(100% - 40px);
      overflow: auto;
      .tree-left {
        width: 100%;
        height: 100%;
      }
      .el-tree {
        width: 100%;
        height: 100%;
      }
    }
  }
  .center {
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding: 0 5px;
    :deep(.el-button + .el-button) {
      margin-top: 10px;
      margin-left: 0px;
    }
  }
  .right {
    width: 50%;
    height: 100%;
    display: flex;
    flex-direction: column;
    border: 1px solid #dcdfe6;
    padding-left: 10px;
    .tree-box {
      min-width: 430px;
      flex: 1;
      flex-shrink: 0;
      overflow: auto;
      .el-tree {
        width: 100%;
        height: 100% !important;
      }
    }
  }
  .content-juan {
    padding: 10px 0;
  }
}
:deep(.el-vl__window) {
  height: 100% !important;
}
:deep(.el-vl__wrapper) {
  height: 100% !important;
}
</style>
